// areaLists, baseList
// import {subwayList} from "../../../utils/data/enterPrise"
import {postCert, getmy, getAllArea, getAllsubway, getAllBasicService } from '../../../utils/api/module/task';
import { upLoadFile} from "../../../utils/api/module/upload";
import config from '../../../config';
Page({
    data: {
        URL: config._URL_,
        statusSub: 0,
        statusAuth: 0,
        imgs: {
            statusEdit: "https://ythapi.bjyangshu.com/public/images/editSh.png",    //编辑状态
            statusIng: "https://ythapi.bjyangshu.com/public/images/shengheIng.png",  //审核中
            statuserr: '/assets/img/1111.png',  //审核失败
            statused: "https://ythapi.bjyangshu.com/public/images/shengheed.png",   //审核通过
            selIcon: "/assets/img/icon_left.png",
            photoFil: "/assets/img/lsheader.png",
            toastClose: '/assets/img/close_icon.png',
            unSel: '/assets/img/unselect.png',  //未选中状态
            seled: '/assets/img/selected.png',  //选中状态
        },
        // 资料填写/修改的数据
        companyName: '',  //企业名称
        brandName:'',    //品牌名称
        licenseZm:'', //执照正面的图片地址
        callUser: '',  //联系人姓名
        callPhone: '',  //联系方式号码
        workType: '', // 职位
        workLocalDetail: '', //详细地址
        companyDesc: '',   //企业简介

        // 选择地址
        regIndex: '1a0',
        positionFlag: true,
        area: null,
        //企业类型选择数据
        companyList: [{name:"园区", id: 1},{name: "创业企业", id: 2}, {name: "第三方服务企业", id: 3}],
        toastFlag: true,
        companyType: {name:'请选择企业类型', id: 0},  //企业类型
        //基础服务
        baseList: [],  //选择的项目
        //园区区域
        areaLists: [],
        //园区地铁
        subwayList: [],
        //园区简介
        yqDesc: '',
        //园区名称
        yqName: '',
        //园区图片
        yqPuicture: [],
        //logo
        logo: '',
        auditInformation: {}, // 审核信息

    },
    onLoad: function (optionsbaseCheck) {
        this.getAllBasicService();
    },
    /**
     * 双向绑定企业名称
     * @param e
     */
    modelCompanyName(e){
        this.setData({
            companyName: e.detail.value,
        })
    },
    /**
     * 双向绑定品牌名称
     */
    modelBrandNameVal(e){
        this.setData({
            brandName: e.detail.value,
        })
    },
    /**
     * 获取所有区域接口
     * @return {[type]}
     */
    getAllArea: function() {
        getAllArea().then(res => {
            let data = res.data.data;
            data.map(item => {
                item.checked = false;
            });
            this.data.areaLists = res.data.data
            this.getAllsubway();
        });
    },
    // 获取所有地铁线路接口
    getAllsubway: function() {
        getAllsubway().then(res => {
            let data = res.data.data;
            data.map(item => {
                item.checked = false;
            });
            this.data.subwayList = data;
            this.getMyInfo();
        });
    },
    // 获取基础服务
    getAllBasicService: function() {
        getAllBasicService().then(res => {
            let data = res.data.data;
            data.map(item => {
                item.checked = false;
            });
            this.getAllArea();
            this.data.baseList = data;
        })
    },
    /**
     * 点击选择企业类型
     */
    selectCompanyType(){
        this.setData({
            toastFlag: false,
        })
    },
    /**
     * 关闭选择企业类型的弹窗
     */
    closeToast(e){
        this.setData({
            toastFlag: true,
            companyType: e.detail
        })
    },
    /**
     * 点击选择地址
     */
    selectAddress(){
        this.setData({
            positionFlag: false
        })
        let animation = wx.createAnimation({
            duration: 300,
            timingFunction: 'linear'
        })
        this.animation = animation
        animation.translateY(0).step()
        setTimeout(() => {
            this.setData({
                animationData: this.animation.export()
            })
        }, 200)
    },
    /**
     * 地址选择显示，隐藏的动画方法
     */
    unshade() {
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: 'linear'
        })
        this.animation = animation
        animation.translateY(306).step()
        this.setData({
            animationData: this.animation.export()
        })
        setTimeout(() => {
            this.setData({
                positionFlag: true
            })
        }, 100)
    },
    /**
     * 监听选择地址完毕以后的方法
     * @param e
     */
    onCalendarChange(e) {
        this.setData({
            regIndex: 258,
            area: e.detail.provinceName + e.detail.cityListName + e.detail.areaListName,
            ['form.nursing_workers_province']: e.detail.provinceNameId,
            ['form.nursing_workers_city']: e.detail.cityListId,
            ['form.nursing_workers_town']: e.detail.areaListId
        })
    },
    /**
     * 点击上传营业执照的正面
     */
    clickPhotoZm(){
        let that = this;
        wx.chooseImage({
            count: 1, // 限制只能上传一张图片
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success (res) {
                
                // tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = res.tempFilePaths[0];
                //上传图片的方法
                that.uploadimg(tempFilePaths);
            }
        })
        // this.callCamera();
    },
    
    callCamera(){
        let that = this;
        wx.showActionSheet({
            itemList: ['拍照', '从相册选择'],
            success (res) {
                //拍照
                if(res.tapIndex == 0){
                    
                    return false;
                };
                //从相册中获取
                if(res.tapIndex == 1){
                    wx.chooseImage({
                        count: 1, // 限制只能上传一张图片
                        sizeType: ['original', 'compressed'],
                        sourceType: ['album'],
                        success (res) {
                            // tempFilePath可以作为img标签的src属性显示图片
                            const tempFilePaths = res.tempFilePaths[0];
                            //上传图片的方法
                            that.uploadimg(tempFilePaths);
                        }
                    })
                }
            },
            fail (res) {
                // console.log(res.errMsg)
            }
        })
    },
    /**
     * 上传营业执照的
     * @param fileName
     * @param params
     */
    uploadimg(fileName){
        let that = this;
        upLoadFile({
            formData:{
                "mid": wx.getStorageSync('userInfo').mid
            },
            filePath: fileName,
        },{
            "Cookie": 'SESSION_='+wx.getStorageSync('session_id'),
        }).then(res => {
            //data == 字符串，转换成JSON格式，方便使用里面的值。
            let resData = JSON.parse(res.data);
            if(resData.code == 1 ){
                that.setData({ licenseZm: resData.data.url})
            }
        }).catch(err => {
            wx.showToast({title: "上传失败，请重新尝试", icon: "none" })
        })
    },
    /**
     * 上传logo
     */
    upLoadLogo(){
        let that = this;
        wx.chooseImage({
            count: 1, // 限制只能上传一张图片
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res){
                // tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = res.tempFilePaths[0];
                //上传图片的方法
                upLoadFile({
                    formData:{
                        "mid": wx.getStorageSync('userInfo').mid
                    },
                    filePath: tempFilePaths,
                },{
                    "Cookie": 'SESSION_='+wx.getStorageSync('session_id'),
                }).then(res => {
                    //data == 字符串，转换成JSON格式，方便使用里面的值。
                    let resData = JSON.parse(res.data);
                    that.setData({
                        logo: resData.data.url
                    })
                }).catch(err => {
                    wx.showToast({title: "上传失败，请重新尝试"})
                })
            }
        })
    },
    /**
     * 上传园区
     */
    upLoadYqPicture(){
        let that  = this;
        wx.chooseImage({
            count: 9 - this.data.yqPuicture.length, // 限制只能上传一张图片
            sizeType: ['original', 'compressed'],
            sourceType: ['album',"camera"],
            success (res) {
                // tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = res.tempFilePaths;
                 that.recurveUpload11111({
                    mid: wx.getStorageSync('userInfo').mid,
                    path: tempFilePaths
                }, (path) => {
                    that.setData({
                        yqPuicture: that.data.yqPuicture.concat(path)
                    })
                })
                //上传图片的方法
                // upLoadFile({
                //     formData:{
                //         "mid": wx.getStorageSync('userInfo').mid
                //     },
                //     filePath: tempFilePaths,
                // },{
                //     "Cookie": 'SESSION_='+wx.getStorageSync('session_id'),
                // }).then(res => {
                //     //data == 字符串，转换成JSON格式，方便使用里面的值。
                //     let resData = JSON.parse(res.data);
                //     that.setData({
                //         yqPuicture: resData.data.url
                //     })
                // }).catch(err => {
                //     wx.showToast({title: "传失败，请重新尝试"})
                // })

            }
        })
    },
    // 多图上传
    recurveUpload11111(data, callback){
        let that = this,
            i = data.i? data.i : 0,   //当前上传的哪张图片
            success = data.success ? data.success : 0,   //上传成功的个数
            fail = data.fail ? data.fail : 0;    //上传失败的个数
        let images = data.images ? data.images : [];
        wx.showLoading({
            title: `正在上传第${i}张`
        })
        try {
            upLoadFile({
                formData:{
                    "mid": wx.getStorageSync('userInfo').mid
                },
                filePath: data.path[i],
            },{
                "Cookie": 'SESSION_='+wx.getStorageSync('session_id'),
            }).then(res => {
                //data == 字符串，转换成JSON格式，方便使用里面的值。
                success++; //图片上传成功，图片上传成功的变量+1
                let data = JSON.parse(res.data);
                // images.push(config._URL_ +'/'+data.data.url);
                images.push(data.data.url);
            }).catch(err => {
                fail++; //图片上传失败，图片上传失败的变量+1
            }).finally(()=>{
                i++;   //这个图片执行完上传后，开始上传下一张
                if (i == data.path.length) { //当图片传完时，停止调用
                    wx.hideLoading({
                        success() {
                            wx.showToast({
                                title: '上传完成',
                                icon: 'none',
                                duration: 2200
                            })
                            if (typeof (callback) == "function") {
                                callback(images);
                            }
                        }
                    })
                } else { //若图片还没有传完，则继续调用函数
                    data.i = i;
                    data.images = images;
                    data.success = success;
                    data.fail = fail;
                    that.recurveUpload11111(data, callback);
                }
            })
        }catch (e) {
            console.log(e);
        }
    },
    /**
     * 双向绑定联系人value
     * @param e
     */
    modelCallUser(e){
        this.setData({
            callUser: e.detail.value,
        })
    },
    /**
     * 双向绑定联系点还value
     * @param e
     */
    modelCallPhone(e){
        this.setData({
            callPhone: e.detail.value,
        })
    },
    /**
     * 双向绑定职位value
     * @param e
     */
    modelWorkType(e){
        this.setData({
            workType: e.detail.value,
        })
    },
    /**
     * 双向绑定地址详情value
     * @param e
     */
    modelWorkLocalDetatil(e){
        this.setData({
            workLocalDetail: e.detail.value,
        })
    },
    /**
     * 双向绑定获取到企业简介内容
     */
    getCompanyDesc(e){
        this.setData({
            companyDesc:e.detail.value
        })
    },
    /**
     * 修改资料并认证
     */
    alertAndAuthentication(){
        this.setData({statusSub: 0})
    },
    /**
     * 选择基础服务
     */
    baseCheck(e){
        let idx = e.currentTarget.dataset.idx;
        let arrs = this.data.baseList;
        arrs[idx].checked= !arrs[idx].checked;
        this.setData({
            baseList: arrs
        })
    },
    /**
     * 园区类型时， 选择园区地域
     * @param e
     */
    yqAreaCheck(e){
        let idx =e.currentTarget.dataset.idx;
        let arrs = this.data.areaLists;
        arrs.map((item ,index)=> {
            if(idx == item.id) {
                item.checked = true;
            }else{
                item.checked = false;
            }
        })

        this.setData({
            areaLists: arrs,
        })
    },
    /**
     * 园区类型时，选择园区地体
     * @param e
     */
    subwayCheck(e){
        let idx =e.currentTarget.dataset.idx;
        let arrs = this.data.subwayList;
        arrs.map(item => { if(idx == item.id) item.checked = !item.checked; });
        this.setData({ subwayList: arrs });
    },
    /**
     * 双向绑定园区名称
     * @param e
     */
    modelYqNameVal(e){
        this.setData({
            yqName: e.detail.value,
        })
    },
    /**
     * 双向绑定园区简介
     * @param e
     */
    modelYqDescVal(e){
        this.setData({
            yqDesc: e.detail.value,
        })
    },
    /**
     * 确认提交
     */
    submitConfirm(){
        let {companyName, brandName, callUser, callPhone, workType, area, workLocalDetail, companyDesc,licenseZm, companyType, baseList, areaLists, subwayList, yqName, yqDesc, yqPuicture, logo} = this.data;
        let baseStr = '', subwayStr='',areaVal='';
        baseList.forEach(item => {
            if(item.checked ) baseStr = !baseStr ? item.id : baseStr + ',' + item.id;
        })
        subwayList.forEach(item => {
            if(item.checked) subwayStr = !subwayStr ?  item.id : subwayStr + ',' + item.id 
        })
        areaLists.forEach(item =>{
            if(item.checked) areaVal=item.id
        })
        // return false
        console.log("企业名称 == > ",companyName);
        console.log("品牌名称 == > ",brandName);
        console.log("企业类型 == > ",companyType);
        console.log("基础服务 == > ",baseList);
        console.log("营业执照URL == > ",licenseZm);
        console.log("联系人 == > ",callUser);
        console.log("联系人手机 == > ",callPhone);
        console.log("职务 == > ",workType);
        // console.log("办公地址 == > ",yqPuicture.join('|'));
        console.log("详细地址 == > ",workLocalDetail);
        console.log("企业简介 == > ",companyDesc);
        console.log("园区地域id====>",areaVal );
        console.log("园区地铁====>", subwayList);
        console.log("园区名称====>", yqName);
        console.log("园区简介====>", yqDesc);
        console.log('园区基础服务------->', baseStr)
        console.log('园区地铁选择------->', subwayStr)
        console.log('园区地铁选择------->', logo)
        postCert({
            mid: wx.getStorageSync('userInfo').mid,
            companyname:companyName,
            brandname:brandName,
            membertype: companyType.id,
            cert:licenseZm,  //营业执照
            contact: callUser,  //联系人
            phone: callPhone,   //联系人电话
            position: workType,  //联系人职务
            address: workLocalDetail,  //地址
            intro: companyDesc, // 企业简介
            parktitle: yqName,
            parkstitle:yqDesc,
            parkpic: yqPuicture.join('|'),
            basicservice:baseStr,
            area: areaVal,
            subway:subwayStr,
            logo: logo
        },{
            Cookie: 'SESSION_='+wx.getStorageSync('session_id'),
        }).then(res => {
            if(res.data.code == 1) {
                this.setData({ statusSub: 1 });
                this.getMyInfo();
                return false;
            };
            if(res.data.code == 0) wx.showToast({title: res.data.message, icon: 'none'})
        });
    },
    /**
     * 获取信息
     */
    getMyInfo(){
        getmy({
            mid: wx.getStorageSync('userInfo').mid,
        },{
            Cookie: 'SESSION_='+wx.getStorageSync('session_id'),
        }).then(res => {
            /**
             * 使用res.data.data.type == 1 来判断是否是园区类型的；
             * 如果是type == 1 为园区类型； 在页面中展示 res.data.data.parkinfo中的数据
             * 如果type！= 1 res.data.data.parkinfo是一个空对象
             */
            
            let data = res.data.data;
            let { companyList } = this.data;
            let type = data.type;
            let companyType = '';
            companyList.forEach(item => {
                if(data.type == item.id) {
                    companyType= item;
                }
            })
            // 判断是否已经认证
            if(res.data.data.certstatus !=0){
                /**
                 * 处理一下地铁数据
                 * @type {Object}
                 */
                let subwayList = type == 1 ? data.parkinfo.subway : data.subway;
                let rzInfo ={
                    companyType: companyType,
                    workLocalDetail: type == 1? data.parkinfo.address:data.address,
                    brandName: type == 1? data.parkinfo.brandname: data.brandname,
                    licenseZm: type == 1? data.parkinfo.cert : data.cert,
                    statusSub: type == 1? data.parkinfo.certstatus : data.certstatus,
                    companyName: type == 1? data.parkinfo.companyname:data.companyname,
                    companyDesc: type == 1? data.parkinfo.  intro:data.intro,
                    lastTime: type == 1? data.parkinfo.lasttime:data.lasttime,
                    loginNum: type == 1? data.parkinfo.loginnum:data.loginnum,
                    // parkinfo: data.parkinfo,
                    callUser: type == 1? data.parkinfo.mcontact:data.contact,
                    callPhone: type == 1? data.parkinfo.mphone:data.phone,
                    workType: type == 1? data.parkinfo.mposition:data.position,
                    regtime: type == 1? data.parkinfo.regtime:data.regtime,
                    salt: type == 1? data.parkinfo.salt:data.salt,
                    status: type == 1? data.parkinfo.status:data.status,
                    username: type == 1? data.parkinfo.username:data.username,
                    logo: type == 1? data.parkinfo.logo:data.logo,
                    // logo: type == 1? data.parkinfo.pic:data.pic,
                    yqName: type == 1? data.parkinfo.title:data.title,
                    yqDesc: type == 1? data.parkinfo.stitle:data.stitle,
                    yqPuicture: type == 1 ? data.parkinfo.pic.split('|') : data.pic.split('|'),
                    yqBaseServe: type == 1? data.parkinfo.basicservice:data.basicservice,
                    yqSubway: subwayList ? subwayList.split(",") : [],
                    yqareaName: type == 1? data.parkinfo.areaname:  data.areaname,
                    area: type == 1? data.parkinfo.area:  data.area
                }
                if(type==1){
                    if(rzInfo.statusSub!=0){
                        this.data.subwayList.map((item,index) => {
                            rzInfo.yqSubway.map( items => {
                                if(item.id == Number(items)) {
                                    this.data.subwayList[index].checked = true
                                };
                            });
                        });
                        this.data.areaLists.map(item => {
                            if(item.id == rzInfo.area) item.checked = true;
                        });
                        this.data.baseList.map(item => {
                            rzInfo.yqBaseServe.map(items => {
                                if(item.id == items.id) item.checked = true;
                            });
                        });

                    }
                } 
                this.setData(rzInfo);
            }
            this.setData({ areaLists: this.data.areaLists, subwayList: this.data.subwayList, baseList: this.data.baseList });
        })
    },
    bindClose(e) {
        let index = e.currentTarget.dataset.index,
            self = this;
        wx.showModal({
            title: '提示',
            content: '是否删除该图片。',
            cancelText: '取消',
            cancelColor: '#999999',
            confirmText: '确认',
            confirmColor: '#2878f8',
            success: res => {
              if (res.confirm) {
                wx.showToast({ title: '删除成功', icon: 'none', duration: 2200 })
                self.data.yqPuicture.splice(index, 1);
                self.setData({ yqPuicture: self.data.yqPuicture });
              } else if (res.cancel) {
                return false;
              };
            }
        });
    }
});